package com.huan.es8.documentapi;

import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import com.huan.es8.AbstractEs8Api;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 批量操作Document
 *
 * @author huan.fu
 * @date 2022/11/1 - 21:27
 */
public class BulkApi extends AbstractEs8Api {

    @Test
    @DisplayName("批量插入文档")
    public void bulkOperation() throws IOException {
        Person p1 = new Person("1001","张三",20,"湖北省罗田县");
        Person p2 = new Person("1002","李四",35,"湖北省英山县");
        Person p3 = new Person("1003","王武",30,"湖北省罗田县匡河镇");

        List<BulkOperation> bulkOperations  = new ArrayList<>(3);

        for (Person person : Arrays.asList(p1, p2, p3)) {
            BulkOperation bulkOperation = BulkOperation.of(operation ->
                    operation.create(create -> create.id(person.getId()).index("index_person").document(person)));
            bulkOperations.add(bulkOperation);
        }

        BulkResponse bulkResponse = client.bulk(builder -> builder.operations(bulkOperations));

        System.out.println(bulkResponse);

    }

    @AllArgsConstructor
    @Getter
    static class Person {
        private String id;
        private String name;
        private Integer age;
        private String address;
    }
}
